package com.dynasty;

/**
 * @description 模拟死锁
 * Created by wangchao12 on 2019/4/24 17:13.
 */

public class DeadLock implements Runnable {
    private int a = 1;
    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public DeadLock(int a) {
        this.a = a;
    }

    @Override
    public void run() {
        if (1 == a) {
            synchronized (o1) {
                System.out.println("a = " + a + "获取了o1的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("a = " + a + "获取了o2的锁");
                }
            }
        } else {
            synchronized (o2) {
                System.out.println("a = " + a + "获取了o2的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("a = " + a + "获取了o1的锁");
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLock deadLock1 = new DeadLock(1);
        DeadLock deadLock2 = new DeadLock(2);
        Thread thread1 = new Thread(deadLock1);
        Thread thread2 = new Thread(deadLock2);
        thread1.start();
        thread2.start();
    }
}
